package cn.com.sparkle.paxos.net.callback;

import cn.com.sparkle.paxos.NodeState;
import cn.com.sparkle.paxos.event.EventsManager;
import cn.com.sparkle.paxos.event.NodeStateChangeEvent;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.ElectionId;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.Id;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.MessagePackage;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.SenatorHeatBeatResponse;
import cn.com.sparkle.paxos.net.CallBack;
import cn.com.sparkle.paxos.net.NetNode;

public class HeatBeatCallBack implements CallBack {
	private EventsManager eventsManager;
	public HeatBeatCallBack(EventsManager eventsManager){
		this.eventsManager = eventsManager;
	}
	@Override
	public void call(NetNode nnode, MessagePackage value) {
		if (value.hasSenatorHeartBeatResponse()) {
			SenatorHeatBeatResponse res = value
					.getSenatorHeartBeatResponse();
			NodeState nodeState = nnode.getNodeState();
			nodeState.setLastBeatHeatTime(System.currentTimeMillis());
			nodeState.setMasterConnected(res.getIsMasterConnected());
			// nodeState.setLastElectionId(new
			// ElectionId(res.getElectionId(), res.getElectionAddress(),
			// res.getElectionVersion()));
			nodeState.setLastElectionId(ElectionId
					.newBuilder()
					.setId(Id.newBuilder()
							.setIncreaseId(res.getElectionId())
							.setAddress(res.getElectionAddress()))
					.setVersion(res.getElectionVersion()).build());
			nodeState.setLastCanExecuteInstanceId(res
					.getLastCanExecuteInstanceId());
			NodeStateChangeEvent.doBeatHeartEvent(eventsManager, nodeState);
		} else {
			throw new RuntimeException("unexception error:no response!");
		}
	}

	@Override
	public void fail(NetNode nnode) {
	}
}